<?php

namespace app\api\v1\controller;

use app\api\v1\validate\common\IdValidate;
use app\api\v1\validate\content\category\CategoryByAudioListValidate;
use app\api\v1\validate\content\category\CategoryListValidate;
use app\api\v1\validate\media\banner\GetBannerListValidate;
use app\api\v1\validate\order\goods\GoodsListValidate;
use app\common\ApiBase;
use app\common\SmsType;
use app\model\AppConfig;
use app\model\AppHome;
use app\model\HomeButton;
use app\model\Smslog;
use app\service\QCloudCosService;
use app\service\SmsService;
use polymerize\content\service\ArticleService;
use polymerize\content\service\CategoryService;
use polymerize\media\service\BannerService;
use polymerize\order\service\GoodsService;
use support\Log;
use support\Redis;
use support\Request;
use support\Response;
use think\db\exception\DataNotFoundException;
use think\db\exception\DbException;
use think\db\exception\ModelNotFoundException;

class Whole extends ApiBase
{
    /**
     * 文件上传
     *
     * @param Request $request
     * @return Response
     */
    public function uploadPic(Request $request): Response
    {
        $files = $request->file('file');
        if (empty($files)) return $this->apiFailed('获取上传数据错误');

        try {
            $res = QCloudCosService::instance()->upload($files);
        } catch (\Throwable $e) {
            return $this->apiFailed('上传失败' . $e->getMessage());
        }

        return $this->apiSuccess($res);
    }

    /**
     * banner列表
     *
     * @param Request $request
     * @return Response
     */
    public function banner(Request $request): Response
    {
        $validate = new GetBannerListValidate();
        if (!$validate->check($request->post())) return $this->apiFailed($validate->getError());

        $page  = $request->post('page', 1);
        $limit = $request->post('limit', 10);

        $res = BannerService::getInstance()->getBannerList((int)$request->uid, (int)$page, (int)$limit);

        return $this->apiSuccess($res);
    }

    /**
     * 发送短信
     *
     * @param Request $request
     * @return Response
     */
    public function sendSms(Request $request): Response
    {
        $count = Smslog::getCount([['id', '>', 0]]) ?? 0;
        if ($count > env('SMS_COUNT', '900')) return $this->apiFailed('短信额度不足');

//        $check = $this->checkAesTime();
//        if (is_string($check)) return $this->apiFailed($check);
        $osType = $request->post('os_type', 0);
        $type   = $request->post('type', 'reg');
        $mobile = $request->post('mobile', '');
        if (empty($mobile)) return $this->apiFailed('请填写手机号');
        if (!is_mobile(($mobile))) return $this->apiFailed('手机号码格式错误');
        //1分钟请求频率限制
        $expire_time = 59;
        $lock_key    = 'sendSms_' . md5($type . $request->uuid);
        //判断key不存在时，为 key 设置指定的值
        $lock = Redis::setNx($lock_key, 1);
        //设置key时间
        Redis::expire($lock_key, $expire_time);
        if (!$lock) return $this->apiFailed('请等待倒计时结束');
        //key 的剩余过期时间在重新设置过期时间防止死锁
        if (Redis::ttl($lock_key) == -1) Redis::expire($lock_key, $expire_time); //防止死锁
        $typeName = '';
        switch ($type) {
            //登录注册
            case 'reg':
//                $_send = SmsService::instance()->send_sms($mobile, SmsType::SMS_CODE_API_LOGIN->value);
//                $_send = SmsService::instance()->send_sms_chuanglang($mobile, SmsType::SMS_CODE_API_LOGIN->value);
                $_send    = SmsService::instance()->send_sms_shansuma($mobile, SmsType::SMS_CODE_API_LOGIN->value);
                $typeName = '登录注册';
                break;
            //绑定手机号
            case 'bind_mobile':
                $_send    = SmsService::instance()->send_sms_shansuma($mobile, SmsType::SMS_CODE_BIND_MOBILE->value);
                $typeName = '绑定手机号';
                break;
            //解除手机号
            case 'relieve_mobile':
                $_send    = SmsService::instance()->send_sms_shansuma($mobile, SmsType::SMS_CODE_RELIEVE_MOBILE->value);
                $typeName = '解除手机号';
                break;
            //修改密码
            case 'change_password':
                $_send    = SmsService::instance()->send_sms_shansuma($mobile, SmsType::SMS_CODE_CHANGE_PASSWORD->value);
                $typeName = '修改密码';
                break;
            default:
                return $this->apiFailed();
        }
        if ($_send->code != 'OK') return $this->apiFailed($_send->message);

        //短信日志
        $data = [
            'mobile'  => $mobile,
            'content' => $typeName,
            'os_type' => $osType,
            'c_time'  => myDate(),
        ];
        $res  = Smslog::insert($data);

        if (!$res) (Log::channel('applepaylog'))->info('短信日志', '写入失败' . json_encode($data));

        return $this->apiSuccess([], '发送成功');
    }

}